package net.yyge.manifest.editor;

import net.yyge.manifest.editor.tag.*;
import org.w3c.dom.*;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class ManifestXml {

    public Document document;
    public UsesSdkTag usesSdk;
    public ActivityTag activity;
    public UsesPermissionTag usesPermission = null;
    public PermissionTag permission = null;
    public ManifestTag manifest;
    public ApplicationTag application;
    public ProviderTag provider;

    public ManifestXml(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
            // 将字符串包装成 InputSource
            InputSource is = new InputSource(new StringReader(xmlStr));
            document = builder.parse(is); // ✅ 正确方式解析字符串
        } catch (ParserConfigurationException | SAXException | IOException e) {
            throw new RuntimeException(e);
        }

        document.getDocumentElement().normalize(); // 标准化文档
        usesPermission = new UsesPermissionTag(document); //初始化 UsesPermission
        activity = new ActivityTag(document); //初始化 UsesPermission
        permission=new PermissionTag(document);
        provider=new ProviderTag(document); //初始化 provider

        NodeList nodeList = document.getElementsByTagName("uses-sdk");
        Element  usesSdkEle= (Element) nodeList.item(0);
        usesSdk = new UsesSdkTag(usesSdkEle);

        NodeList activityList = document.getElementsByTagName("activity");
        for (int i = 0; i < activityList.getLength(); i++) {
            Element element = (Element)activityList.item(i);
            activity.initActivity(element);
        }

        NodeList providerList = document.getElementsByTagName("provider");
        for (int i = 0; i < providerList.getLength(); i++) {
            Element element = (Element)providerList.item(i);
            provider.initProvider(element);
        }

        NodeList usesPermissionList = document.getElementsByTagName("uses-permission");
        for (int i = 0; i < usesPermissionList.getLength(); i++) {
            Element element = (Element) usesPermissionList.item(i);
            usesPermission.initPermission(element);
        }

        NodeList permissionList = document.getElementsByTagName("permission");
        for (int i = 0; i < permissionList.getLength(); i++) {
            Element element = (Element) permissionList.item(i);
            permission.initPermission(element);
        }

        NodeList manifestList = document.getElementsByTagName("manifest");
        manifest = new ManifestTag((Element) manifestList.item(0));


        NodeList applicationList = document.getElementsByTagName("application");
        application = new ApplicationTag((Element) applicationList.item(0));
    }


    public void setSdkVersion(Integer min, Integer max) {
        System.out.println(document);

//        item.setAttribute("xx","666");
//        System.out.println(item);
//        NodeList elementsByTagName = document.getElementsByTagName("uses-sdk");
//        String string = innerXML(document);
//        System.out.println(string);
        System.out.println("XML 文件加载并解析完成。根元素: " + document.getDocumentElement().getNodeName());
    }




    /**
     * 将 Document 对象转换为格式化的 XML 字符串
     */
    public  String innerXML() {
        // 使用 StringWriter 接收输出
        StringWriter writer = new StringWriter();
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            // 设置输出属性
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");                     // 使用 XML 方法
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");                 // 编码
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");                     // 启用缩进
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // 缩进空格数
            transformer.transform(new DOMSource(this.document), new StreamResult(writer));

        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }

        return writer.toString();
    }

    public ApplicationTag getApplication() {
        return application;
    }

    public UsesPermissionTag getUsesPermission() {
        return usesPermission;
    }

    public PermissionTag getPermission() {
        return permission;
    }

    public ManifestTag getManifest() {
        return manifest;
    }

    public UsesSdkTag getUsesSdk() {
        return usesSdk;
    }


    public ProviderTag getProvider() {
        return this.provider;
    }


    public ActivityTag getActivity() {

        return activity;
    }
}
